const couponLogModel = require('../../model/couponLogModel')
require('../../model/couponModel')
require('../../model/usersModel')
const { check_page } = require('../../utils/checkType')

//获取领取记录
module.exports.get = async function (req, res, next) {
    const params = req.body
    let couponLogCondition = {show:true}
    
    if (params.state) {
        couponLogCondition = Object.assign({}, couponLogCondition, { state: params.state })
    }
    if (params.title) {
        couponLogCondition = Object.assign({}, couponLogCondition, { title: { $regex: params.title, $options: '$i' } })
    }
    if (params.nickname) {
        couponLogCondition = Object.assign({}, couponLogCondition, { nickname: { $regex: params.nickname, $options: '$i' } })
    }
    let data = []
    try {
        data = await couponLogModel.find(couponLogCondition).populate('userId').populate('couponId')

    } catch (error) {
        console.log(error);
        console.log('获取领取记录');
        res.send({
            meta: {
                msg: '获取领取记录,参数有误',
                status: 202,
            }
        });
        return false;
    } 
    if (data.length) {
        //分页
        let total = data.length
        if (check_page(params.limit)&&check_page(params.page)) {
            data = data.filter((item, index) => index < params.limit * params.page && index >= params.limit * (params.page - 1))
        } else if(params.limit && params.page) {
            res.send({
                meta: {
                    msg: 'limit,page参数错误',
                    status: 202
                }
            });
            return false
        }
        res.send({
            data,
            total,
            meta: {
                msg: '查询成功',
                status: 200
            }
        });
        return false;
    } else {
        res.send({
            meta: {
                msg: '查询失败，没有数据',
                status: 201
            }
        });
        return false;
    }
}